import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/services.dart';

const times = 10000;
void main() {
  testWidgets('Test keyboard input in a TextField',
      (WidgetTester tester) async {
    // 准备测试
    await tester.pumpWidget(MaterialApp(home: MyTextField()));

    // 找到文本字段
    Finder textFieldFinder = find.byType(TextField);
    expect(textFieldFinder, findsOneWidget);

    // 输入文本
    var txt = '';
    for(var i = 0; i < times; i++) {
      txt += 'a';
      await tester.enterText(textFieldFinder, 'a');
    }
    await tester.pump(); // 刷新界面以便测试者可以看到变化

    // 验证文本是否已经输入
    expect(find.text(txt), findsOneWidget);
  });


  testWidgets('Test Input Box Enter', (WidgetTester tester) async {
    // 准备测试
    await tester.pumpWidget(MaterialApp(home: EnterTextField()));

    // 找到显示按钮并点击
    for (var i = 0; i < times; i++) {
      await tester.tap(find.text('Show Dialog'));
      await tester.pump(); // 更新视图以显示弹窗

      // 检查弹窗是否显示
      expect(find.text('Alert Dialog'), findsOneWidget);
      expect(find.text('This is an alert dialog.'), findsOneWidget);
      expect(find.text('OK'), findsOneWidget);
    }
    print('END');
    // await waiting();
  });
}

class MyTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: TextField(),
      ),
    );
  }
}

class EnterTextField extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          key: const Key('my-text-field'),
          child: Text('Show Dialog'),
          onPressed: () async {
            await showDialog(
                context: context,
                builder: (BuildContext context) {
                  return AlertDialog(
                    title: const Text('Alert Dialog'),
                    content: Text('This is an alert dialog.'),
                    actions: [
                      TextButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          child: const Text('OK'))
                    ],
                  );
                });
          },
        ),
      ),
    );
  }
}

Future<int> waiting() async {
  int num = 0;
  await Future.delayed(Duration(milliseconds: 10000), () {
    num = num + 1;
  });
  return num;
}
